<script setup>
	import { ref } from 'vue'
	import dataConnectorApi from '@/views/plugin/dashboard/api/dataConnectorApi'
	import ConnectorList from './ConnectorList.vue'
	import DataConnectorForm from './DataConnectorForm.vue'
	import ConnectorDetail from './components/ConnectorDetail.vue'

	const selectedConnector = ref(null)
	const connectorStatus = ref('checking')
	const dataConnectorFormRef = ref(null)
	const connectorListRef = ref(null)
	const connectorDetailRef = ref(null)

	const handleConnectorSelect = (node) => {
		selectedConnector.value = node
		connectorStatus.value = 'checking'
		// 校验连接器状态
		dataConnectorApi
			.testConnection(node.data)
			.then(() => {
				connectorStatus.value = 'normal'
			})
			.catch(() => {
				connectorStatus.value = 'error'
			})
	}

	// 编辑连接器
	const handleEdit = (connectorData) => {
		dataConnectorFormRef.value.open(connectorData)
	}

	// 删除连接器
	const handleDelete = (connectorId) => {
		// 清空选中的连接器
		selectedConnector.value = null
		// 触发ConnectorList组件刷新
		if (connectorListRef.value?.loadTreeData) {
			connectorListRef.value.loadTreeData()
		}
	}

	// 处理表单成功事件
	const handleFormSuccess = async () => {
		// 触发ConnectorList组件刷新
		if (connectorListRef.value?.loadTreeData) {
			connectorListRef.value.loadTreeData()
		}

		// 如果当前有选中的连接器，需要更新其详情信息
		if (selectedConnector.value?.data?.id) {
			await refreshSelectedConnectorInfo()
		}
	}

	// 刷新选中连接器的详细信息
	const refreshSelectedConnectorInfo = async () => {
		if (!selectedConnector.value?.data?.id) return

		try {
			// 重新获取连接器列表，找到当前选中的连接器
			const connectorList = await dataConnectorApi.list()
			const updatedConnector = connectorList.find((item) => item.id === selectedConnector.value.data.id)

			if (updatedConnector) {
				// 更新选中连接器的数据，保持原有的树节点结构
				selectedConnector.value = {
					...selectedConnector.value,
					title: updatedConnector.name,
					data: updatedConnector
				}

				// 重新测试连接状态
				connectorStatus.value = 'checking'
				try {
					await dataConnectorApi.testConnection(updatedConnector)
					connectorStatus.value = 'normal'
				} catch (error) {
					connectorStatus.value = 'error'
				}

				console.log('连接器信息已更新:', updatedConnector.name)
			}
		} catch (error) {
			console.error('刷新连接器信息失败:', error)
		}
	}
</script>

<template>
	<div>
		<div class="flex h-full bg-white">
			<!-- 左侧连接器列表 -->
			<ConnectorList ref="connectorListRef" :onConnectorSelect="handleConnectorSelect" />
			<!-- 右侧连接器信息 -->
			<div class="flex-1 p-6">
				<template v-if="selectedConnector">
					<ConnectorDetail
						ref="connectorDetailRef"
						:connector="selectedConnector"
						:status="connectorStatus"
						@delete="handleDelete"
						@edit="handleEdit"
					/>
				</template>
				<div v-else class="h-full flex items-center justify-center text-gray-400">请选择左侧连接器查看详细信息</div>
			</div>
		</div>

		<!-- 数据连接器表单 -->
		<DataConnectorForm ref="dataConnectorFormRef" @success="handleFormSuccess" />
	</div>
</template>

<style scoped></style>
